package com.dingpeikeji.quickdeer.mobile.service;

import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.line.service.TLineService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FDemandsService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.google.common.collect.Lists;

@Service
@Transactional(readOnly = true)
public class MobileDayRentService {
	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private OrderService orderService;

	public BackResult getDayRentList(TRentproduct tRentproduct, HttpServletRequest request,
			HttpServletResponse response, Model model, TCargotype tCargotype,String pageNo,String pageSize) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		//日期处理
		String fromdate = request.getParameter("fromdatestr");
		String[] arr = fromdate.split("\\s");
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 获取车型
		tCargotype.setTstyles(request.getParameter("tstyle"));
		tRentproduct.setCargotype(tCargotype);
		// 如果发车日期为空或者小于当前日期，则设置成明天  包车天数为空，1天-10天选择，默认1天
		tRentproduct.handleFromDate(model).handleDaysnum();
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(tRentproduct, request, "f");
		// 分页对象
		Page<TCargotype> page = new Page<TCargotype>(request, response);
		tCargotype.setPage(page);
		page.setPageSize(Integer.parseInt(pageSize));
		page.setPageNo(Integer.parseInt(pageNo));
		// 跨市range=2,市内range=1(t_rentgroup表)
		if (tRentproduct.getTabType().equals("市内")) {
			tCargotype.setRange("1");
		} else {
			tCargotype.setRange("2");
		}
		List<TCargotype> cargotypeList = rentproductService.findCargotypeList(tCargotype);
		page.setList(cargotypeList);
		// 获取车型id,查询对应的线路报价
		List<TRentproduct> rentproductList = null;
		if (cargotypeList.size() > 0) {
			for (TCargotype tc : cargotypeList) {
				tRentproduct.setCargotype(tc);
				// 市内日租包车
				if (TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType())
						&& tRentproduct.getTabType().equals("市内")) {
					rentproductList = rentproductService.findInCityList(tRentproduct);
					if (tRentproduct.getDaysnum()==0) {//0.5天,计算价格
						for (TRentproduct rp : rentproductList) {
							rp.setSuitrtnprice(Math.rint(rp.getSuitrtnprice()*0.8));
						}
						
					}
				}
				// 跨城日租包车
				if (TOrders.ORDER_TYPE_RENTPRODUCT_DAY.equals(tRentproduct.getRentType())
						&& tRentproduct.getTabType().equals("跨市")) {
					rentproductList = rentproductService.findBetweenCityList(tRentproduct);
				}
				tc.setRentproductList(rentproductList);
			}
			map.put("cargotypeList", cargotypeList);
			map.put("totalCount", page.getCount()+"");
			return BackResult.ok(map);
		}else{
			return BackResult.build("400", "未查询到数据");
		}
	}
	//按天包车订单填写
	public BackResult genDayRentOrderData(TRentproduct tRentproduct, Model model, HttpServletRequest request) throws Exception {
		Map<String,Object> map = new HashMap<String, Object>();
		// 根据ID查询选中的整车信息
		TRentproduct rentproduct = tRentproductService.get(tRentproduct.getRentid());
		TRentgroup rentgroup = tRentgroupService.getMobileRentgroup(rentproduct.getRentgrpid());
		if (rentproduct==null||rentgroup==null) {
			return BackResult.build("400", "参数有误");
		}
		//日期处理
		String fromdate = request.getParameter("fromdateStr");
		String[] arr = fromdate.split("\\s");
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 协议价逻辑处理
		TRentproduct query = new TRentproduct();
		query.setRentid(tRentproduct.getRentid());
		query.setDepartdate(DateUtils.parseDate(request.getParameter("fromdatestr")));
		// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
		rentproductService.setCompAgreerateOffice(query, request, "f");
		query = rentproductService.getSuitrtnprice(query);
		rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		if (tRentproduct.getDaysnum()==0) {
			rentproduct.setSuitrtnprice(Math.rint(query.getSuitrtnprice()*0.8));
		}
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		map.put("tRentproduct", rentproduct);
		map.put("rentgroup", rentgroup);
		map.put("fromdateStr",fromdate );
		map.put("query", tRentproduct);
		return BackResult.ok(map);
	}
	//按天包车订单提交
	public BackResult submitDayRentOrder(CuponsInfo cuponsInfo,TOrders orders, Model model, 
			HttpServletRequest request) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		orders.setOrderuserid(request.getParameter("userid"));
		// 消息集合
		List<String> messages = Lists.newArrayList(); // 消息
		TRentproduct tRentproduct = new TRentproduct();
		//手机端传入日期格式 2000-01-01 06:00
		String fromdateStr = request.getParameter("fromdateStr");
		String[] arr = fromdateStr.split("\\s");//按空格切割
		tRentproduct.setFromdateStr(arr[0]);
		tRentproduct.setTime(arr[1]);
		// 如果发车日期为空或者小于当前日期，则设置成明天
		tRentproduct.handleFromDate(model);
		if (messages.isEmpty()) {
			TRentproduct query = new TRentproduct();
			query.setRentid(Integer.parseInt(orders.getRealscheid()));
			query.setDepartdate(DateUtils.parseDate(orders.getDepartdateStr()));
			orders.setDepartdate(query.getDepartdate());//Fri Aug 25 06:00:00 CST 2017
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			Double suitrtnprice = query.getSuitrtnprice();
			if (orders.getBookingdays()==0) {
				suitrtnprice = Math.rint(suitrtnprice * 0.8);//四舍五入取整
			}
			orders.setDueamount("" + suitrtnprice);
			Integer purchasenum = Integer.valueOf(orders.getPurchasenum());
			if (orders.getOrdertype().equals(TOrders.ORDER_TYPE_RENTPRODUCT_DAY)) {
				if (orders.getBookingdays()==0) {
					orders.setDueamount("" + Math.rint(query.getSuitrtnprice()*0.8 * 1 * purchasenum));
				}else{
					orders.setDueamount("" + query.getSuitrtnprice() * orders.getBookingdays() * purchasenum);
				}
			} else {
				orders.setDueamount("" + query.getSuitrtnprice() * purchasenum);
			}
			//使用优惠券,减去优惠金额
			if(StringUtils.isNotEmpty(cuponsInfo.getCuponsId())){
				int price = Integer.parseInt(request.getParameter("money"));
				double orderPrice = Double.parseDouble(orders.getDueamount());
				orders.setDueamount("" +(orderPrice - price));
			}
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(orders);
				if (pro.success()) { // 如果成功生成订单，跳到支付方式选择页面
					Integer orderid = pro.getOrderid();
					orders.setOrderid(orderid+"");
					map.put("orders", orders);
					//改变优惠券使用状态
					if(cuponsInfo.getCuponsId()!=null&&cuponsInfo.getCuponsId().length()>0){
						CuponsInfo a = tCuponsService.getCuponsByRecordId(cuponsInfo.getCuponsId());
						if(Double.parseDouble(orders.getDueamount())+Double.parseDouble(cuponsInfo.getMoney())<Double.parseDouble(a.getMinPrice())){
							return BackResult.build("400", "提交失败");
				    	}
						orderService.updateOrderUseCupon(orders.getOrderid());
						cuponsInfo.setOrderId(orders.getOrderid());
						cuponsInfo.setUseTime(new Date());
						tCuponsService.useCupon(cuponsInfo);
					}
					return BackResult.ok(map);
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		return BackResult.build("400", messages.get(0));
	}
}
